﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using WeatherReader;
using System.Globalization;

public partial class MonthlyData : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            LoadCombo();
            LoadMonthlyData(DateTime.Today);
        }
    }


    private void LoadCombo()
    {
        var weatherDb = new WeatherDbDataContext();
        var months = from raw in weatherDb.HouseholdDatas
                     group raw by new { raw.Month, raw.Year, } into monthData
                     select new { monthData.Key.Month, monthData.Key.Year, MinDay = monthData.Min(m => m.Date) }
                      ;

        cboDate.DataSource = months.OrderByDescending(m => m.MinDay);
        cboDate.DataValueField = "MinDay";
        cboDate.DataTextField = "MinDay";
        //cboDate.DataTextFormatString = "{y}";
        cboDate.DataBind();

    }

    private void LoadMonthlyData(DateTime dayInMonth)
    {
        int month = dayInMonth.Month;
        int year = dayInMonth.Year;

        var weatherDb = new WeatherDbDataContext();

        string title = string.Format("Weather and CO2 emissions for {0}", dayInMonth.ToString("MMM yyyy"));

        lblMonth.Text = title;
        Page.Title = title;
        var monthlyReadings = weatherDb.HouseholdDatas.Where(h => h.Month == month && h.Year == year);

        chartCo2.DataSource = monthlyReadings;

        DateTime firstDayInMonth = new DateTime(dayInMonth.Year, dayInMonth.Month, 1);
        chartCo2.ChartAreas["ChartArea1"].AxisX.Minimum = 1;
        chartCo2.ChartAreas["ChartArea1"].AxisX.Maximum = 31;
        chartCo2.ChartAreas["ChartArea1"].AxisY.Maximum = 40;
        chartCo2.DataBind();

        
      


        var monthlyTempReadings = weatherDb.AllDailyWeatherDatas.Where(s => s.ReadingDate >= firstDayInMonth && s.ReadingDate < firstDayInMonth.AddMonths(1));
        //chartTemp.Visible = monthlyTempReadings.Count() > 0;
        
        chartTemp.DataSource = monthlyTempReadings;
        chartTemp.ChartAreas["ChartArea1"].AxisX.Minimum = firstDayInMonth.ToOADate();
        chartTemp.ChartAreas["ChartArea1"].AxisX.Maximum = firstDayInMonth.AddMonths(1).AddDays(-1).ToOADate();
        chartTemp.ChartAreas["ChartArea1"].AxisX.LabelStyle.Format = "{0:d}";
        chartTemp.DataBind();


        PressureChart.DataSource = monthlyTempReadings;
        PressureChart.ChartAreas["ChartArea1"].AxisX.Minimum = firstDayInMonth.ToOADate();
        PressureChart.ChartAreas["ChartArea1"].AxisX.Maximum = firstDayInMonth.AddMonths(1).AddDays(-1).ToOADate();
        PressureChart.ChartAreas["ChartArea1"].AxisX.LabelStyle.Format = "{0:d}";

        //var maxPressure =((int) monthlyTempReadings.Where(p => p.MaxTemp!= null).Max(p => p.MaxTemp).Value) * 1.1;
        //var minPressure = ((int)monthlyTempReadings.Where(p => p.MinTemp != null).Min(p => p.MinTemp).Value) * 0.9;
        PressureChart.ChartAreas["ChartArea1"].AxisY.Minimum = 960;
        PressureChart.ChartAreas["ChartArea1"].AxisY.Maximum = 1040;

        PressureChart.DataBind();


        if (monthlyReadings.Count() >= monthlyTempReadings.Count())
        {
        var combinedReadings = from h in monthlyReadings
                               join t in monthlyTempReadings on h.Date equals t.ReadingDate
                               into tempReadings
                               from readings in tempReadings.DefaultIfEmpty()
                               select new
                               {
                                   h.Date,
                                   h.ElectricityCo2,
                                   h.ElectricityKwh,
                                   h.GasCo2,
                                   h.GasKwh,
                                   h.Co2,
                                   readings.AvgTemp,
                                   readings.MaxTemp,
                                   readings.MinTemp,
                                   readings.DegreeDays,
                                   readings.KwhPerDegreeDay,
                                   TotalEnergy = h.ElectricityKwh + h.GasKwh,
                                   EnergyRate = (h.ElectricityKwh + h.GasKwh)/24
                               };
            dgData.DataSource = combinedReadings;
        }
        else
        {
              var combinedReadings = from t in monthlyTempReadings
                               join h in monthlyReadings  on t.ReadingDate  equals h.Date
                               into tempReadings
                               from readings in tempReadings.DefaultIfEmpty()
                               select new
                               {
                                   Date = t.ReadingDate,
                                   readings.ElectricityCo2,
                                   readings.ElectricityKwh,
                                   readings.GasCo2,
                                   readings.GasKwh,
                                   readings.Co2,
                                   t.AvgTemp,
                                   t.MaxTemp,
                                   t.MinTemp,
                                   t.DegreeDays,
                                   t.KwhPerDegreeDay,
                                   TotalEnergy = (readings.ElectricityKwh + readings.GasKwh),
                                   EnergyRate = (readings.ElectricityKwh + readings.GasKwh) / 24
                               };
            dgData.DataSource = combinedReadings;
        }
        


        dgData.DataBind();


    }
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        //DateTime dtReadingDate = DateTime.Parse(txtDate.Text, CultureInfo.CreateSpecificCulture("en-GB").DateTimeFormat);
        //LoadMonthlyData(dtReadingDate);

    }
    protected void cboDate_SelectedIndexChanged(object sender, EventArgs e)
    {
        DateTime dtReadingDate = DateTime.Parse(cboDate.SelectedValue, CultureInfo.CreateSpecificCulture("en-GB").DateTimeFormat);
        LoadMonthlyData(dtReadingDate);
    }
}
